package com.cgc.venus.server.core.harbor;

import com.cgc.venus.server.core.bean.response.VenusResponseStatus;
import com.cgc.venus.server.core.exception.VenusException;
import com.cgc.venus.server.core.harbor.client.HarborClient;
import com.cgc.venus.server.core.harbor.model.Project;
import com.cgc.venus.server.core.harbor.model.Repository;
import com.cgc.venus.server.core.harbor.model.Tag;
import com.cgc.venus.server.core.utils.DateUtil;
import com.cgc.venus.server.core.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 业哥 on 2017/9/13.
 */
@Service
public class HarborServiceImpl implements HarborService {
    @Autowired
    private HarborClient harborClient;

    /**
     * 判断是否登录
     *
     * @return
     */
    private boolean isLogin() throws VenusException {
        boolean f=true;
        if(f){
            return false;
        }
        CookieStore cookieStore = harborClient.getCookieManager().getCookieStore();
        List<HttpCookie> httpCookies = cookieStore.getCookies();
        if (httpCookies != null) {
            for (HttpCookie httpCookie : httpCookies) {
                String name = httpCookie.getName();
                if ("beegosessionID".equals(name)) {
                    String value = httpCookie.getValue();
                    if (StringUtil.isEmpty(value)) {
                        return false;
                    }
                    if(httpCookie.hasExpired()){
                        return false;
                    }
                }
            }
        }
        return true;
    }

    private void login() throws VenusException {
        if (!isLogin()) {
            try {
                harborClient.login(harborClient.getAdminUser(), harborClient.getAdminPassword());
            } catch (IOException e) {
                throw new VenusException(VenusResponseStatus.HARBOR_EXCEPTION, "调用harbor服务器网络异常!");
            }
        }
    }

    /**
     * 查询项目
     *
     * @param projectName
     * @param isPublic
     * @return
     */
    @Override
    public List<Project> projectsQuery(String projectName, boolean isPublic) throws VenusException {
        login();
        List<Project> projects = null;
        try {
            projects = harborClient.getProjects(projectName, isPublic, "", 1, 100);
        } catch (IOException e) {
            throw new VenusException(VenusResponseStatus.HARBOR_EXCEPTION, e.getMessage());
        }
        return projects;
    }

    @Override
    public boolean projectsCreate(String projectName, boolean isPublic) throws VenusException {
        try {
            login();
            return harborClient.createProject(projectName, isPublic);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean projectsDelete(String projectName) throws VenusException {
        login();
        try {
            boolean f = harborClient.deleteProject(projectName);
            return f;
        } catch (IOException e) {
            throw new VenusException(VenusResponseStatus.HARBOR_EXCEPTION, e.getMessage());
        }
    }


    @Override
    public boolean repositoryDelete(String resName) throws VenusException {
        login();
        try {
            boolean f = harborClient.deleteRepositories(resName);
            return f;
        } catch (IOException e) {
            throw new VenusException(VenusResponseStatus.HARBOR_EXCEPTION, e.getMessage());
        }
    }
    @Override
    public boolean repositoryDelete(String resName,String tag) throws VenusException {
        login();
        try {
            boolean f = harborClient.deleteRepositories(resName,tag);
            return f;
        } catch (IOException e) {
            throw new VenusException(VenusResponseStatus.HARBOR_EXCEPTION, e.getMessage());
        }
    }


    @Override
    public List<Tag> getRepositorieTags(String imagesAddress, String repoName) throws VenusException {
        login();
        if(StringUtil.isEmpty(imagesAddress)){
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "镜像地址为空!");
        }
        if(StringUtil.isEmpty(repoName)){
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "镜像名称为空!");
        }
        List<Tag> tags= null;
        try {
            tags = harborClient.getRepositorieTags(repoName);
        } catch (IOException e) {
            throw new VenusException(VenusResponseStatus.IO_EXCEPTION, "io 异常!");
        }
        if(tags!=null&&tags.size()>0){
            for(Tag tag:tags){
                if(imagesAddress.endsWith("/")){
                    tag.setPullCmd("docker pull "+imagesAddress+repoName+":"+tag.getName());
                }else{
                    tag.setPullCmd("docker pull "+imagesAddress+"/"+repoName+":"+tag.getName());
                }
                tag.setCreated(DateUtil.zoneDateTimeStrConvertToShangHaiTimeStr("yyyy-MM-dd HH:mm",tag.getCreated()));
            }
            return tags;
        }
        return null;
    }

    /*
    * 根据项目名称,查询镜像资源列表
    * */
    @Override
    public List<Repository> getRepositories(String projectName, String repositoryNameQueryKey, int page, int page_size) throws VenusException {
        login();
        if (StringUtil.isEmpty(projectName)) {
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "项目名称为空!");
        }
        List<Repository> repositoryList = new ArrayList<Repository>();
        try {
            repositoryList = harborClient.getRepositories(projectName,repositoryNameQueryKey,page,page_size);
            if (repositoryList.size() > 0) {
                repositoryList.forEach(repository -> {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                    try {
                        Date d = format.parse(repository.getCreationTime());
                        format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        repository.setCreationTime(format.format(d));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                });
            }
        } catch (IOException e) {
            throw new VenusException(VenusResponseStatus.IO_EXCEPTION, "io 异常!");
        }
        return repositoryList;
    }
}